<template>
    <div class="login-page">
        <div class="mobile-bg hidden-sm-and-up"></div>
        <div class="desktop-bg hidden-xs-only"></div>
        <el-row class="login-container">
            <!-- 左侧背景图 -->
            <el-col :xs="0" :sm="10" :md="10" :lg="10" :xl="10" class="left-panel hidden-xs-only">
                <div class="background-image"></div>
            </el-col>

            <!-- 右侧登录注册表单 -->
            <el-col :xs="24" :sm="14" :md="14" :lg="14" :xl="14" class="right-panel">
                <el-row class="inner">

                    <el-col :span="24">
                        <el-card class="login-form no-border" shadow="never">
                            <!-- 添加语言切换器 -->
                            <div class="lang-selector-container">
                                <lang-selector></lang-selector>
                            </div>
                            <div class="hello-div">{{ $t('login.welcome') }}</br><span class="project_name">{{ $t('login.systemName') }}</span></div>
                            <el-tabs v-model="activeTab" class="login-tabs">
                                <el-tab-pane :label="$t('login.login')" name="login">
                                    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm"
                                        label-width="100px" class="login-form-content">
                                        <el-form-item label-width="auto" :label="$t('login.username')" label-size="20" prop="name">
                                            <el-input :placeholder="$t('login.inputUsername')" type="text" v-model="ruleForm.name"
                                                autocomplete="off" :size="ui_config.input.font_size"
                                                @keyup.enter.native="submitForm('ruleForm')"></el-input>
                                        </el-form-item>
                                        <el-form-item :label="$t('login.password')" label-width="auto" prop="password">
                                            <el-input :placeholder="$t('login.inputPassword')" type="password" v-model="ruleForm.password"
                                                autocomplete="off" :size="ui_config.input.font_size"
                                                @keyup.enter.native="submitForm('ruleForm')"></el-input>
                                        </el-form-item>
                                        <el-form-item label-width="0">
                                            <el-button type="primary" @click="submitForm('ruleForm')"
                                                class="submit-btn">{{ $t('login.login') }}</el-button>
                                        </el-form-item>
                                    </el-form>
                                </el-tab-pane>
                                <el-tab-pane :label="$t('login.register')" name="register">
                                    <el-form :model="formRegister" label-width="100px" :rules="regRule" ref="formRegister" status-icon
                                        class="login-form-content">
                                        <el-form-item label-width="auto" :label="$t('login.username')" prop="name">
                                            <el-input :placeholder="$t('login.inputUsername')" v-model="formRegister.name"
                                                autocomplete="off" :size="ui_config.input.font_size"></el-input>
                                        </el-form-item>
                                        <el-form-item label-width="auto" :label="$t('login.password')" prop="password">
                                            <el-input :placeholder="$t('login.inputPassword')" type="password" v-model="formRegister.password"
                                                autocomplete="off" :size="ui_config.input.font_size"></el-input>
                                        </el-form-item>
                                        <el-form-item :label="$t('login.confirmPassword')" label-width="auto" prop="confirmPassword">
                                            <el-input :placeholder="$t('login.confirmPassword')" type="password" v-model="formRegister.confirmPassword"
                                                autocomplete="off" :size="ui_config.input.font_size"></el-input>
                                        </el-form-item>
                                        <el-form-item label-width="auto" :label="$t('common.email')" prop="mail">
                                            <el-input :placeholder="$t('common.pleaseEnter') + ' ' + $t('common.email')" v-model="formRegister.mail"
                                                autocomplete="off" :size="ui_config.input.font_size"></el-input>
                                        </el-form-item>
                                        <el-form-item label-width="auto" :label="$t('common.telephone')" prop="telephone">
                                            <el-input :placeholder="$t('common.pleaseEnter') + ' ' + $t('common.telephone')" v-model="formRegister.telephone"
                                                autocomplete="off" :size="ui_config.input.font_size"></el-input>
                                        </el-form-item>
                                        <el-form-item label-width="0">
                                            <el-button type="primary" @click="save('formRegister')" class="submit-btn">{{ $t('login.register') }}</el-button>
                                        </el-form-item>
                                    </el-form>
                                </el-tab-pane>
                            </el-tabs>
                        </el-card>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import ElementUI from "element-ui";
import {get, post} from '@/utils/request'
import LangSelector from '@/components/LangSelector.vue'
import { mapMutations } from 'vuex'


export default {
    name: "Login",
    components: {
        LangSelector
    },
    data() {
        // 用户名验证
        const validateName = (rule, value, callback) => {
            if (value === "") {
                callback(new Error(this.$t('login.inputUsername')));
            }
            setTimeout(() => {
                callback();
            }, 100);
        };

        // 密码验证
        const validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error(this.$t('login.inputPassword')));
            }
            setTimeout(() => {
                callback();
            }, 100);
        };

        // 确认密码验证
        const validateConfirmPass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error(this.$t('login.confirmPassword')));
            } else if (value !== this.formRegister.password) {
                callback(new Error(this.$t('login.passwordMismatch')));
            } else {
                callback();
            }
        };

        // 邮箱验证
        const validateEmail = (rule, value, callback) => {
            if (value === "") {
                callback(new Error(this.$t('common.pleaseEnter') + ' ' + this.$t('common.email')));
            } else {
                const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
                if (!emailRegex.test(value)) {
                    callback(new Error(this.$t('login.invalidEmail')));
                } else {
                    callback();
                }
            }
        };

        // 电话验证
        const validatePhone = (rule, value, callback) => {
            if (value === "") {
                callback();
            } else {
                const phoneRegex = /^1[3-9]\d{9}$/;
                if (!phoneRegex.test(value)) {
                    callback(new Error(this.$t('login.invalidPhone')));
                } else {
                    callback();
                }
            }
        };

        return {
            ui_config: {
                input: {
                    font_size: "large"
                }
            },
            activeTab: 'login', // 默认激活登录标签页
            // 登录表单
            ruleForm: {
                name: "admin",
                password: "123456"
            },
            // 注册表单
            formRegister: {
                name: "",
                password: "",
                confirmPassword: "",
                mail: "",
                telephone: ""
            },
            // 登录验证
            rules: {
                name: [{ validator: validateName, trigger: "blur" }],
                password: [{ validator: validatePass, trigger: "blur" }],
            },
            // 注册验证
            regRule: {
                name: [{ validator: validateName, trigger: "blur" }],
                password: [{ validator: validatePass, trigger: "blur" }],
                confirmPassword: [{ validator: validateConfirmPass, trigger: "blur" }],
                mail: [{ validator: validateEmail, trigger: "blur" }],
                telephone: [{ validator: validatePhone, trigger: "blur" }]
            },
        };
    },

    methods: {
        ...mapMutations(['SET_TOKEN', 'SET_USERINFO', 'SET_USERID']),
        
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    const _this = this;
                    
                    // 使用封装的post方法
                    post("/account/login", {
                        name: this.ruleForm.name,
                        password: this.ruleForm.password
                    }).then((response) => {
                        // 检查响应状态
                        if (response.data.code !== 200) {
                            ElementUI.Message.error(response.data.msg || this.$t('login.loginFailed'));
                            return;
                        }
                        
                        // 获取headers中的数据
                        const jwt = response.headers["authorization"];
                        if (!jwt) {
                            console.error("登录成功但未获取到token");
                            ElementUI.Message.error(this.$t('login.loginFailed'));
                            return;
                        }
                        
                        const userInfo = response.data.data;
                        
                        // 将token存入sessionStorage而不是localStorage
                        sessionStorage.setItem("token", jwt);
                        
                        // 使用mapMutations映射的方法
                        this.SET_TOKEN(jwt);
                        this.SET_USERINFO(userInfo);
                        this.SET_USERID(userInfo.userId);
                        
                        // 显示登录成功消息
                        ElementUI.Message.success(this.$t('login.loginSuccess'));
                        
                        // 跳转
                        _this.$router.push("/home");
                    }).catch(error => {
                        console.error("登录请求出错:", error);
                        // 检查是否有响应数据
                        if (error.response && error.response.data) {
                            ElementUI.Message.error(error.response.data.msg || this.$t('login.loginFailed'));
                        } else {
                            ElementUI.Message.error(this.$t('login.loginFailed'));
                        }
                    });
                } else {
                    return false;
                }
            });
        },

        // 添加用户
        save(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 创建一个新对象，不包含confirmPassword字段
                    const userData = {
                        name: this.formRegister.name,
                        password: this.formRegister.password,
                        mail: this.formRegister.mail,
                        telephone: this.formRegister.telephone,
                        status: 1, // 默认状态为正常
                        groupId: 1 // 默认班级为1
                    };
                    
                    // 根据API文档，注册接口为 /user/add
                    post("/user/add", userData).then(res => {
                        // 成功处理 - 拦截器已经确保了成功响应
                        ElementUI.Message.success(this.$t('login.registerSuccess'));
                        this.formRegister = {
                            name: "",
                            password: "",
                            confirmPassword: "",
                            mail: "",
                            telephone: ""
                        };
                        // 切换到登录标签页
                        this.activeTab = 'login';
                    }).catch(error => {
                        // 错误已经在拦截器中处理，这里可以添加额外的处理
                        console.error("注册失败:", error);
                    });
                } else {
                    return false;
                }
            });
        },
    },
};
</script>

<style scoped>
.login-page {
    min-height: 100vh;
    position: relative;
    overflow: hidden;
}

.mobile-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url("@/assets/background.jpg") no-repeat center;
    background-size: cover;
    z-index: -1;
}

.desktop-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url("@/assets/background.jpg") no-repeat center;
    background-size: cover;
    z-index: -1;
}

.hello-div {
    font-size: 1.0em;
    /* padding-left: 15px; */
    /* text-align: center; */
    /* margin-bottom: 30px; */
    color: #333;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.project_name {
    color: #409EFF;
    font-size: 1.8em;
    display: block;
    margin-top: 10px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.no-border {
    border: none !important;
}

::v-deep .el-card__header {
    border-bottom: none;
}

.login-container {
    height: 100vh;
    overflow: hidden;
}

.left-panel {
    height: 100vh;
}

.background-image {
    height: 100%;
    background: url("@/assets/background.jpg") no-repeat center;
    background-size: cover;
}

.right-panel {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 20px;
    background: rgba(255, 255, 255, 0.95);
}

.right-panel .inner {
    max-width: 500px;
    width: 100%;
    position: relative;
}

.lang-selector-container {
    text-align: right;
    padding: 10px;
    margin-bottom: 20px;
}

/* 调整语言选择器的样式 */
::v-deep .lang-selector {
    display: inline-block;
}

::v-deep .el-dropdown-link {
    color: #409EFF;
    cursor: pointer;
    font-size: 14px;
}

::v-deep .el-dropdown-link:hover {
    color: #66b1ff;
}

/* 登录表单样式 */
.login-form {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 15px;
    /* padding: 30px; */
    padding: 0 30px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-tabs {
    margin-top: 20px;
}

.login-form-content {
    padding: 20px 0;
}

.submit-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    margin-top: 20px;
    border-radius: 22px;
    background: linear-gradient(45deg, #409EFF, #66b1ff);
    border: none;
    transition: all 0.3s ease;
}

.submit-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
    .hello-div {
        font-size: 1.5em;
        padding: 0;
        margin-bottom: 20px;
    }

    .project_name {
        font-size: 1.2em;
    }

    .right-panel {
        padding: 0 15px;
        background: rgba(255, 255, 255, 0);
    }

    .login-form {
        padding: 15px;
    }

    .login-form-content {
        padding: 15px 0;
    }

    ::v-deep .el-form-item__label {
        float: none;
        display: block;
        text-align: left;
        padding: 0 0 8px;
        line-height: 1.5;
    }

    ::v-deep .el-form-item__content {
        margin-left: 0 !important;
    }

    .submit-btn {
        height: 44px;
        font-size: 16px;
    }
}

/* 超小屏幕适配 */
@media screen and (max-width: 480px) {
    .hello-div {
        font-size: 1.5em;
    }

    .project_name {
        font-size: 1.1em;
    }

    .right-panel {
        padding: 0 10px;
    }

    .login-form {
        padding: 10px;
    }

    .login-form-content {
        padding: 10px 0;
    }
}
</style>